import { utils } from 'xlsx'

export function decode_range_prop (sheet) {
  let sc = 999999999
  let ec = 0
  let sr = 999999999
  let er = 0

  const keys = Object.keys(sheet)

  for (const key of keys) {
    if (key.startsWith('!')) continue
    const cr = separateLettersAndNumbers(key)
    if (cr.c > ec) ec = cr.c
    else if (cr.c < sc) sc = cr.c
    if (cr.r > er) er = cr.r
    else if (cr.r < sr) sr = cr.r
  }

  // SheetJS Range interface
  return {
    s: {
      c: sc,
      r: sr,
    },
    e: {
      c: ec,
      r: er,
    },
  }
}

function separateLettersAndNumbers (str) {
  const regex = /([A-Z]+)(\d+)/ // 匹配字母和数字
  const match = str.match(regex)

  if (match) {
    return {
      c: utils.decode_col(match[1]), // 字母部分
      r: Number(match[2]),  // 数字部分
    }
  }

  return null // 如果没有匹配，返回 null
}